'use strict';

/**
 * @ngdoc function
 * @name youaBiDashboardAngularApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the youaBiDashboardAngularApp
 */
angular.module('youaBiDashboardAngularApp')
	.controller('OrderCtrl', function($scope, $http, $location) {
		this.awesomeThings = [
			'HTML5 Boilerplate',
			'AngularJS',
			'Karma'
		];

		var username = window.localStorage.getItem('username');
		var csrftoken = window.localStorage.getItem('csrftoken');

		if (!username || !csrftoken) {
			return $location.path('/login')
		}

		$http({
			method: 'POST',
			url: '/user/checkUserLogin',
			params: {
				username: username,
				csrftoken: csrftoken
			}
		}).then(function successCallback(response) {
			var result = response.data.result;
			if (!result) {
				window.localStorage.removeItem('username')
				window.localStorage.removeItem('csrftoken')

				return $location.path('/login')
			}
		});

		$scope.logout = function () {
			var username = window.localStorage.getItem('username');

			$http({
				method: 'POST',
				url: '/user/logout',
				params: {
					username: username
				}
			}).then(function successCallback(response) {
				var result = response.data.result;
				if (result) {
					window.localStorage.removeItem('username')
					window.localStorage.removeItem('csrftoken')

					return $location.path('/login')
				}
			})
		}

		$scope.template = {
			sidebar: "views/sidebar.html",
			header: "views/header.html"
		}

		$scope.periodRadio = 'day'

		$scope.inlineOptions = {
			minDate: new Date(),
			showWeeks: true
		};

		$scope.dateOptions = {
			formatYear: 'yy',
			maxDate: new Date(2020, 5, 22),
			startingDay: 1
		};

		$scope.popup = {
			opened: false
		};

		$scope.start = null;
		$scope.end = null;

		var getStartToEnd = function(period, date) {

			var map = {
				'day': function () {
					$scope.start = moment(date).format('YYYY-MM-DD');
					$scope.end = moment(date).format('YYYY-MM-DD');
				},

				'week': function () {
					$scope.start = moment(date).isoWeekday("Monday").format('YYYY-MM-DD');
					$scope.end = moment(date).isoWeekday("Sunday").format('YYYY-MM-DD')
				},

				'month': function () {
					var year = moment(date).format('YYYY');
				    var month = moment(date).format('MM');
				    var endday = getEndOfMonth(year, month);

				    $scope.start = moment().year(year).month(parseInt(month)-1).date(1).format('YYYY-MM-DD');
				    $scope.end = moment().year(year).month(parseInt(month)-1).date(endday).format('YYYY-MM-DD');
				}
			}

			var fn = map[period];
			if (_.isFunction(fn)) {
				fn()
			}
		}



		$scope.format = 'yyyy-MM-dd';
		$scope.altInputFormats = 'yyyy-MM-dd';
		$scope.dt = Date.now();

		$scope.summery = {}

		$scope.open = function() {
			$scope.popup.opened = true;
		}

		var getEndOfMonth = function(year, month) {
			var map = {
				'01': 31,
				'02': function(year, month) {
					if (year % 4 == 0) {
						return 29
					} else {
						return 28
					}
				},
				'03': 31,
				'04': 30,
				'05': 31,
				'06': 30,
				'07': 31,
				'08': 31,
				'09': 30,
				'10': 31,
				'11': 30,
				'12': 31
			}

			return _.isFunction(map[month]) ? map[month](year, month) : map[month];
		}

		var timemap = {
			'week': function(date) {
				return ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
			},

			'month': function(date) {
				var year = moment(date).format('YYYY');
				var month = moment(date).format('MM');
				var end = getEndOfMonth(year, month);
				var arr = [];
				for (var i = 1; i < end + 1; i++) {
					arr.push(i);
				}
				return arr
			}
		}

		$scope.ordernum = {
			data: [],
			labels: null,
			series: ['订单数', '支付订单数']
		}

		$scope.paidordernum = {
			data: [],
			labels: null,
			series: ['订单支付金额', '订单实际支付金额'],
			colors: ['#59E817', '#1E711E']
		}

		$scope.payratio = {
			data: [],
			labels: null,
			series: ['订单支付率(%)'],
			colors: ['#7B68EE']
		}

		$scope.pct = {
			data: [],
			labels: null,
			series: ['客单价(元人民币)'],
			colors: ['#134A66']
		}

		$scope.platform = {
			data: [],
			labels: ['Android', 'iOS', 'H5', 'PC'],
			series: ['Android', 'iOS', 'H5', 'PC'],
			colors: ['#DCDCDC', '#46BFBD', '#FDB45C', '#949FB1']
		}

		$scope.userplatform = {
			data: [],
			labels: ['Android', 'iOS', 'H5', 'PC'],
			series: ['Android', 'iOS', 'H5', 'PC'],
			colors: ['#DCDCDC', '#46BFBD', '#FDB45C', '#949FB1']
		}

		$scope.isShowDetail = false;
		$scope.isShowSummery = false;

		$scope.fetch = function() {

			var period = $scope.periodRadio;
			var date = $scope.dt;

			if (!period || !date) {
				return;
			}

			getStartToEnd(period, _.isNumber(date) ? new Date(date) : date)

			var fn = timemap[period];
			if (_.isFunction(fn)) {
				var labels = fn(date);
				$scope.pct.labels = $scope.ordernum.labels = $scope.paidordernum.labels = $scope.payratio.labels = labels;
			}

			$http({
				method: 'GET',
				url: '/order/chart',
				params: {
					period: period,
					timestamp: _.isNumber(date) ? date : date.getTime()
				}
			}).then(function successCallback(response) {

				var summery = response.data.result ? response.data.result.summery : null;
				if (summery) {
					$scope.isShowSummery = true;
					var tmp = _.findWhere(summery, {
						terminal_type: 'TOTAL',
						cps_channel: 'TOTAL'
					});
					var nochannel = _.findWhere(summery, {
						terminal_type: 'TOTAL',
						cps_channel: 'not cps'
					});
					if (tmp) {
						$scope.summery = {
							orderNum: tmp.order_num,
							orderPaidNum: tmp.paid_order_num,
							paidAmount: tmp.payment_amount,
							pct: tmp.pct,
							orderCpsNum: tmp.order_num - nochannel.order_num
						}
					}

					var android = _.findWhere(summery, {
						terminal_type: 'ANDROID'
					});
					var ios = _.findWhere(summery, {
						terminal_type: 'IOS'
					});
					var h5 = _.findWhere(summery, {
						terminal_type: 'H5'
					});
					var pc = _.findWhere(summery, {
						terminal_type: 'PC'
					});
					$scope.platform.data = [android&&android.paid_order_num, ios&&ios.paid_order_num, h5&&h5.paid_order_num, pc&&pc.paid_order_num];
					$scope.userplatform.data = [android&&android.paid_member_num, ios&&ios.paid_member_num, h5&&h5.paid_member_num, pc&&pc.paid_member_num];
				} else {
					$scope.isShowSummery = false;
				}


				var detail = response.data.result ? response.data.result.detail : null;
				if (detail) {
					$scope.isShowDetail = true;

					$scope.ordernum.data = [];
					$scope.paidordernum.data = [];
					$scope.payratio.data = [];
					$scope.pct.data = [];

					var arr = _.filter(detail, function(value, key, list) {
						return value.terminal_type === 'TOTAL' && value.cps_channel === 'TOTAL';
					});

					var orderNumArr = _.pluck(arr, 'order_num');
					var paidOrderNumArr = _.pluck(arr, 'paid_order_num');
					$scope.ordernum.data.push(orderNumArr);
					$scope.ordernum.data.push(paidOrderNumArr);

					var paymentAmountArr = _.pluck(arr, 'payment_amount');
					var paidPaymentArr = _.pluck(arr, 'paid_payment_amount');
					$scope.paidordernum.data.push(paymentAmountArr)
					$scope.paidordernum.data.push(paidPaymentArr)

					var payRatio = []
					for (var i = 0; i < orderNumArr.length; i++) {
						payRatio.push(parseInt(paidOrderNumArr[i] / orderNumArr[i] * 100))
					}
					$scope.payratio.data.push(payRatio);

					var pcts = _.pluck(arr, 'pct');
					$scope.pct.data.push(pcts);
				} else {
					$scope.isShowDetail = false;
				}

			}, function errorCallback(response) {

			});
		}
	});